//
//  DIHTest.m
//  NursingManages
//
//  Created by Zhen Huang on 17/9/13.
//  Copyright © 2017年 huangzhen. All rights reserved.
//

#import "DIHTest.h"
#import "Networking.h"
#import "InitDbTable.h"
#import "UserDefault.h"
#import <TMCache.h>
#import "Model_Hr_ExamContent.h"
#import "HCommon.h"
#import <AFNetworking.h>
@implementation DIHTest


-(instancetype)init{
    
    NSString *url = AppServiceConfig.GetServiceUrl;
    self.downloadUrl  = [NSString stringWithFormat:@"%@/%@?token=%@",url,@"GetExamData",[[TMCache sharedCache] objectForKey:@"deviceToken"]];
    
    return self;
}

- (void)startDownload:(void (^)())callback {
    NSLog(@"开始 下载考试记录");
    
    [Networking receiveDataWithURLString:self.downloadUrl method:@"GET" body:nil Block:^(NSData *tempData) {

        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:tempData options:NSJSONReadingMutableContainers error:nil];
        InitDbTable* initdb = [[InitDbTable alloc]init];
        
        
        Boolean flag =  [[dic valueForKey:@"flag"] boolValue];
        NSString *msg = (NSString*)[dic objectForKey: @"msg"];
        
        if(! flag ){
            
            NSLog(@"%@",msg);
            
            return;
        }
        
        NSDictionary *data = [dic objectForKey: @"data"];
        
        NSArray *data_quebank = [data objectForKey: @"data_quesbank_type"];
        NSArray *data_qestype = [data objectForKey: @"data_question_type"];
//        NSArray *data_queItem = [data objectForKey: @"data_question_item"];
        
        NSMutableArray *arrQueBank = [[NSMutableArray alloc]init];
        NSMutableArray *arrQueType = [[NSMutableArray alloc]init];
        
        for (NSDictionary *diction in data_quebank) {
            Model_Hr_Quesbank_Type *model =[[Model_Hr_Quesbank_Type alloc]initWithDictionary:diction];
            [arrQueBank addObject:model];
        }
        
        for (NSDictionary *diction in data_qestype) {
            Model_Hr_Question_Type *model =[[Model_Hr_Question_Type alloc]initWithDictionary:diction];
            [arrQueType addObject:model];
        }
        
        
        [initdb deleteTest];
        
        
        [initdb inserttest:arrQueBank arrSaType:arrQueType ];
        if(callback){
            callback();
        }
        
    }];

}

- (void) startDownloadQuesWithid:(NSArray *)array
                        downLoad:(void(^)())callback {
    
    
    InitDbTable* initdb = [[InitDbTable alloc]init];
    NSMutableArray *Array = [initdb questype:array];
    [initdb deleteTestWithBankid:Array];

    NSString *url = AppServiceConfig.GetServiceUrl;
    
    // 创建队列组，可以使多个网络请求异步执行，执行完之后再进行操作
    dispatch_group_t group = dispatch_group_create();
    //创建全局队列
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    
    dispatch_group_async(group, queue, ^{

        for (int i = 0; i < array.count; i++) {
            //创建dispatch_semaphore_t对象
            dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
            
            Model_Hr_Quesbank_Type *model = array[i];
            NSString *URL = [NSString stringWithFormat:@"%@/%@?token=%@&BankId=%@",url,@"GetExamDataQues",[[TMCache sharedCache] objectForKey:@"deviceToken"],model.BANKID];
            
            [Networking receiveDataWithURLString:URL method:@"GET" body:nil Block:^(NSData *tempData) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:tempData options:NSJSONReadingMutableContainers error:nil];

                dispatch_semaphore_signal(semaphore);

                Boolean flag =  [[dic valueForKey:@"flag"] boolValue];
                NSString *msg = (NSString*)[dic objectForKey: @"msg"];
                
                                if(! flag ){
                
                                    NSLog(@"%@",msg);
                
                                    return;
                                }
                
                NSDictionary *data = [dic objectForKey: @"data"];
                
                NSArray *data_queItem = [data objectForKey: @"data_question_item"];
                
                NSMutableArray *arrQueItem = [[NSMutableArray alloc]init];
                
                
                
                for (NSDictionary *diction in data_queItem) {
                Model_Hr_Question_Item *model =[[Model_Hr_Question_Item alloc]initWithDictionary:diction];
                [arrQueItem addObject:model];
        
            }
                                
                [initdb insertarrSaItem:arrQueItem];
                if(callback){
                    callback();
            }
                                
                [HCommon popupSuccessMessage:@"下载完成"];
                                
            }];
                

            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        }
    });
    
    // 当所有队列执行完成之后
    dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 执行下面的判断代码
        dispatch_async(dispatch_get_main_queue(), ^{
        });

    });

    
}

- (NSMutableArray *)getQuesBankTitle{
    [DBHelper.DB open];
    
    NSString* sql = [NSString stringWithFormat:@"select * from hr_exam_quebank where parent_id = '*'"];
    NSLog(@"%@",sql);
    FMResultSet *set = [DBHelper.DB executeQuery:sql];
    NSMutableArray *array = [self TransalteToModel:set];
    [DBHelper.DB close];
    return array;

}

- (NSMutableArray *)getQuesBankNameWithBankid:(NSString *)bank_id {
    [DBHelper.DB open];
    
    NSString* sql = [NSString stringWithFormat:@"select * from hr_exam_quebank where parent_id = '%@'",bank_id];
    NSLog(@"%@",sql);
    FMResultSet *set = [DBHelper.DB executeQuery:sql];
    NSMutableArray *array = [self TransalteToModel:set];
    [DBHelper.DB close];
    return array;

}

-(NSMutableArray *) TransalteToModel:(FMResultSet*) set{
    
    NSMutableArray *array = [NSMutableArray array];
    while ([set next]) {
        Model_Hr_Quesbank_Type  *model = [[Model_Hr_Quesbank_Type alloc]init];
        model.BANKID = [set stringForColumn:@"bankid"];
        model.BANKNAME = [set stringForColumn:@"bankname"];
        model.PARENT_ID = [set stringForColumn:@"parent_id"];
        model.DES = [set stringForColumn:@"des"];
        model.INPUT_CODE1 = [set stringForColumn:@"input_code1"];
        model.ORDER_NUM = [set stringForColumn:@"order_num"];
        model.END_FLAG = [set stringForColumn:@"end_flag"];
        model.LEVELS = [set stringForColumn:@"levels"];
        model.QUECOUNT = [set stringForColumn:@"quecount"];
        
        [array addObject:model];
        
    }
    
    return array;
}

- (NSMutableArray *)getQuesWithBankID:(NSString *)bankID {
    [DBHelper.DB open];
    
    NSString* sql = [NSString stringWithFormat:@"select * from hr_exam_questions where bankid = '%@'",bankID];
    
    FMResultSet *set = [DBHelper.DB executeQuery:sql];
    
    //上述方法就是将数据去全部获取放进集合
    NSMutableArray *array = [NSMutableArray array];
    while ([set next]) {
        Model_Hr_Question_Item *model = [[Model_Hr_Question_Item alloc]init];
        model.QUES_ID = [set stringForColumn:@"ques_id"];
        model.TITLE = [set stringForColumn:@"title"];
        model.TYPEID = [set stringForColumn:@"typeid"];
        model.BANKID = [set stringForColumn:@"bankid"];
        model.ANSWER = [set stringForColumn:@"answer"];
        model.CASEID = [set stringForColumn:@"caseid"];
        model.OPTION1 = [set stringForColumn:@"option1"];
        model.OPTION2 = [set stringForColumn:@"option2"];
        model.OPTION3 = [set stringForColumn:@"option3"];
        model.OPTION4 = [set stringForColumn:@"option4"];
        model.OPTION5 = [set stringForColumn:@"option5"];
        model.OPTION6 = [set stringForColumn:@"option6"];
        model.OPTION7 = [set stringForColumn:@"option7"];
        model.OPTION8 = [set stringForColumn:@"option8"];
        model.OPTION9 = [set stringForColumn:@"option9"];
        model.OPTION10 = [set stringForColumn:@"option10"];
        model.ORDER_NUM = [set stringForColumn:@"order_num"];
        model.THOUGHTS = [set stringForColumn:@"thoughts"];
        model.VAL = [set stringForColumn:@"val"];
        model.DIF_LEVEL = [set stringForColumn:@"dif_level"];
        model.ANSWER_FLAG = [set stringForColumn:@"answer_flag"];
        model.answers = [set stringForColumn:@"answers"];
        [array addObject:model];
        
    }
    [DBHelper.DB close];
    return array;
}

- (NSMutableArray *)modelWithTypeId:(NSString *)typeID
{
    [DBHelper.DB open];

    NSString* sql = [NSString stringWithFormat:@"select * from hr_exam_quetype where typeid = '%@'",typeID];
    NSMutableArray *array = [NSMutableArray new];
    FMResultSet *set = [DBHelper.DB executeQuery:sql];
    while ([set next]) {
        Model_Hr_Question_Type *model = [[Model_Hr_Question_Type alloc]init];
        model.TYPEID = [set stringForColumn:@"typeid"];
        model.QUETYPE = [set stringForColumn:@"quetype"];
        model.COMMENTS = [set stringForColumn:@"comments"];
        model.DEFVALUE = [set stringForColumn:@"defvalue"];
        model.ORDER_NUM = [set stringForColumn:@"order_num"];
        [array addObject:model];
    }
    [DBHelper.DB close];

    return array;
}

- (NSMutableArray *)getQuesWithExamID:(NSMutableArray *)examArray {
    
    [DBHelper.DB open];
    
    NSMutableArray *array = [NSMutableArray array];

    for (int i = 0; i < examArray.count; i ++) {
        
        Model_Hr_ExamAnswer *model = examArray[i];
        NSString* sql = [NSString stringWithFormat:@"select * from hr_exam_detail where ques_id = '%@'",model.QUES_ID];
        
        FMResultSet *set = [DBHelper.DB executeQuery:sql];
        
        while ([set next]) {
            Model_Hr_ExamAnswer *model = [[Model_Hr_ExamAnswer alloc]init];
            model.QUES_ID = [set stringForColumn:@"ques_id"];
            model.TITLE = [set stringForColumn:@"title"];
            model.TYPEID = [set stringForColumn:@"typeid"];
            model.BANKID = [set stringForColumn:@"bankid"];
            model.ANSWER = [set stringForColumn:@"answer"];
//            model.CASEID = [set stringForColumn:@"caseid"];
            model.OPTION1 = [set stringForColumn:@"option1"];
            model.OPTION2 = [set stringForColumn:@"option2"];
            model.OPTION3 = [set stringForColumn:@"option3"];
            model.OPTION4 = [set stringForColumn:@"option4"];
            model.OPTION5 = [set stringForColumn:@"option5"];
            model.OPTION6 = [set stringForColumn:@"option6"];
            model.OPTION7 = [set stringForColumn:@"option7"];
            model.OPTION8 = [set stringForColumn:@"option8"];
            model.OPTION9 = [set stringForColumn:@"option9"];
            model.OPTION10 = [set stringForColumn:@"option10"];
            model.ORDER_NUM = [set stringForColumn:@"order_num"];
            model.THOUGHTS = [set stringForColumn:@"thoughts"];
//            model.VAL = [set stringForColumn:@"val"];
//            model.DIF_LEVEL = [set stringForColumn:@"dif_level"];
//            model.ANSWER_FLAG = [set stringForColumn:@"answer_flag"];
//            model.answers = [set stringForColumn:@"answers"];
            
            [array addObject:model];
        }
    }
    [DBHelper.DB close];
    return array;
}

- (NSString *)upDateInspec_new:(Model_Hr_Question_Item *)model {
    
    NSString *sql = [NSString stringWithFormat:@"update hr_exam_questions set answers = '%@' where ques_id = '%@'",model.answers,model.QUES_ID];
    return sql;
}

-(instancetype)modelItem:(Model_Hr_Question_Item *)inspectModel {
    
    NSString *string =   [self upDateInspec_new:inspectModel];
    
    @try {
        
        [DBHelper.DB open];
        [DBHelper.DB beginTransaction];
        
        [DBHelper.DB executeUpdate:string];
        
        [DBHelper.DB commit];
        
        
    } @catch (NSException *exception) {
        
        [DBHelper.DB rollback];
        NSLog(@"发现错误，数据已回滚：%@",exception);
        
    } @finally {
        [DBHelper.DB close];
    }
    
    
    return self;
}

- (instancetype)updateDataWithBankid:(NSString *)bankid
{
    @try {
        
        [DBHelper.DB open];
        [DBHelper.DB beginTransaction];
        NSString *sql = [NSString stringWithFormat:@"update hr_exam_questions set answers = null where answers is not null AND bankid = '%@'",bankid];
        NSLog(@"=%@",sql);

        [DBHelper.DB executeUpdate:sql];
        
        [DBHelper.DB commit];
        
    } @catch (NSException *exception) {
        
        [DBHelper.DB rollback];
        NSLog(@"发生错误，数据已回滚：%@",exception);
        
    } @finally {
        [DBHelper.DB close];
    }
    return self;
}


- (instancetype)updateDataWithQuesid:(NSString *)quesid
{
    @try {
        
        [DBHelper.DB open];
        [DBHelper.DB beginTransaction];
        NSString *sql = [NSString stringWithFormat:@"update hr_exam_questions set answers = null where answers is not null AND ques_id = '%@'",quesid];
        NSLog(@"=%@",sql);
        
        [DBHelper.DB executeUpdate:sql];
        
        [DBHelper.DB commit];
        
    } @catch (NSException *exception) {
        
        [DBHelper.DB rollback];
        NSLog(@"发生错误，数据已回滚：%@",exception);
        
    } @finally {
        [DBHelper.DB close];
    }
    return self;
}


- (NSMutableArray *)getExamBank
{
    [DBHelper.DB open];
    
    NSString* sql = [NSString stringWithFormat:@"select * from hr_exam_quebank where parent_id = '*'"];
    FMResultSet *set = [DBHelper.DB executeQuery:sql];
    NSMutableArray *array = [self TransalteToModel:set];
    [DBHelper.DB close];
    return array;

}

@end
